/* 导入axios */
import axios from 'axios';
import {clearToken, msgConfirm, msgTip} from "../util/util.js";
import {BASE_URL} from "../contants/constants.js";
/* 定义后端接口前缀 */
axios.defaults.baseURL = BASE_URL;

/* 封装基础的http请求 */
/**
 * get请求
 * @param url
 * @param params
 */
export function doGet(url, params) {
    return axios({
        method: 'get',
        url: url,
        params: params,
        dataType: 'json'
    })
}

/**
 * post请求
 * @param url
 * @param data
 * @returns {*}
 */
export function doPost(url, data) {
    return axios({
        method: 'post',
        url: url,
        data: data,
        dataType: 'json'
    })
}

/**
 *
 * @param url
 * @param data
 * @returns {*}
 */
export function doPut(url, data) {
    return axios({
        method: 'put',
        url: url,
        data: data,
        dataType: 'json'
    })
}

/**
 * delete请求
 * @param url
 * @param params
 * @returns {*}
 */
export function doDelete(url, params) {
    return axios({
        method: 'delete',
        url: url,
        params: params,
        dataType: 'json'
    })
}

/**
 * 下载文件
 * @param url
 * @param params
 * @returns {Promise<AxiosResponse<any>> | *}
 */
export function doDownload(url, params) {
    return axios({
        method: 'get',
        url: url,
        params: params,
        responseType: 'blob'
    })
}

/**
 * 请求拦截器
 */
axios.interceptors.request.use(
    config => {
        let tokenName = window.sessionStorage.getItem('tokenName');
        let tokenValue = window.sessionStorage.getItem('tokenValue');
        if(tokenValue && tokenValue) {
            config.headers[tokenName] = tokenValue;
        }
        return config;
    }, error => {
        return Promise.reject(error);
    }
);

/**
 * 响应拦截器
 */
axios.interceptors.response.use(response =>  {
    if(response.data.code === 901) {
        // 这个时候Token有问题
        msgConfirm(response.data.message + ',是否重新登录?').then(() => {
            // 清理token
            clearToken();
            // 清除前端的权限与菜单记录
            window.sessionStorage.removeItem("permission");
            window.sessionStorage.removeItem("menu");
            // 跳转登录页
            window.location.href = '/';
        }).catch(() => {
            msgTip('您已取消登录', 'warning');
        })
        return;
    }
    return response;
},error => Promise.reject(error));